package org.classdef.analyzer.info.constant;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * 常量池
 *
 */
public class ConstantPool {
	
	private List<ConstantInfo> infos = new ArrayList<ConstantInfo>();
	
	public ConstantPool(){
		//第0个位置不存任何数据
		infos.add(null);
	}
	
	public void add(short tag, Object value){
		this.add(tag, 0, value);
	}
	
	public void add(short tag, Object value1, Object value2){
		ConstantInfo info = null;
		switch (tag) {
			case 1:
				info = new Utf8Info(tag, (Short)value1, (byte[])value2);
				break;
			case 3:
				info = new IntInfo(tag, (Integer)value2);
				break;
			case 4:
				info = new FloatInfo(tag, (Float)value2);
				break;
			case 5:
				info = new LongInfo(tag, (Long)value2);
				break;
			case 6:
				info = new DoubleInfo(tag, (Double)value2);
				break;
			case 7:
				info = new ClassInfo(tag, (Short)value2);
				break;
			case 8:
				info = new StringInfo(tag, (Short)value2);
				break;
			case 9:
				info = new FieldRefInfo(tag, (Short)value1, (Short)value2);
				break;
			case 10:
				info = new MethodRefInfo(tag, (Short)value1, (Short)value2);
				break;
			case 11:
				info = new InterfaceMethodRefInfo(tag, (Short)value1, (Short)value2);
				break;
			case 12:
				info = new NameAndTypeInfo(tag, (Short)value1, (Short)value2);
				break;
			case 15:
				info = new MethodHandleInfo(tag, (Byte)value1, (Short)value2);
				break;
			case 16:
				info = new MethodTypeInfo(tag, (Short)value2);
				break;
			case 18:
				info = new InvokeDynamicInfo(tag, (Short)value1, (Short)value2);
				break;
			default:
				return;
		}
		infos.add(info);
		info.setPool(this);
	}
	
	/**
	 * @return infos
	 */
	public List<ConstantInfo> getInfos() {
		return infos;
	}

	/* （非 Javadoc）
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (ConstantInfo info : infos) {
			sb.append(info).append(", ");
		}
		if(sb.length() > 1){
			sb.setLength(sb.length() - 1);
		}
		sb.append("]");
		return sb.toString();
	}
	
	public ConstantInfo get(int index){
		return infos.get(index);
	}
	
}


